import apis from "../services/feedbackApi";

const initData = {
  sceneList: [],
  lineData: [],
  feedbackDetail: [],
  otherCount: {}
};

export default {
  namespace: "feedback",
  state: {
    ...initData
  },
  effects: {
    *fetchSceneList({ payload }, { call, put }) {
      const { action, params } = payload;
      const { errCode, datas = [] } = yield call(apis.fetchSceneList, params) ||
        {};
      if (errCode === 0) {
        yield put({
          type: "updateState",
          payload: { sceneList: datas }
        });
        if (datas.length) {
          yield put({
            type: "fetchTrendData",
            payload: {
              action,
              params: {
                sceneId: datas[0].sceneTemplateId,
                startDate: params.startDate,
                endDate: params.endDate
              }
            }
          });
          yield put({
            type: "fetchFeedBackData",
            payload: {
              sceneId: datas[0].sceneTemplateId
            }
          });
          yield put({
            type: "fetchTopCount",
            payload: { sceneId: datas[0].sceneTemplateId }
          });
        }
      }
      return datas;
    },
    // 推送统计
    *fetchTrendData({ payload }, { call, put }) {
      const { action, params } = payload;
      const { errCode, datas = [] } = yield call(apis[action], params);
      if (errCode === 0) {
        yield put({
          type: "updateState",
          payload: { lineData: datas }
        });
      }
    },

    *fetchFeedBackData({ payload }, { call, put }) {
      const { errCode, datas = [] } = yield call(
        apis.fetchFeedBackDetail,
        payload
      );
      if (errCode === 0) {
        yield put({
          type: "updateState",
          payload: { feedbackDetail: datas }
        });
      }
    },

    *fetchTopCount({ payload }, { call, put }) {
      const { errCode, datas = {} } = yield call(apis.fetchTopCount, payload);
      if (errCode === 0) {
        yield put({
          type: "updateState",
          payload: { otherCount: datas || {} }
        });
      }
    }
  },

  reducers: {
    updateState: (state, { payload }) => ({
      ...state,
      ...payload
    })
  }
};
